import React, { Component } from 'react'
import dayjs from 'dayjs';
import { Button, Card, Table, Modal, Form, Input, Select, message } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { reqUserList, reqAddUser } from "../../api"
import { PAGE_SIZE } from "../../config"
const { Item } = Form
const { Option } = Select
export default class User extends Component {
    state = {
        isShowAdd: false,
        userList: [],
        roleList: []
    }
    showModal = () => {
        this.setState({ isShowAdd: true })
    }
    handleOk = () => {
        this.form.validateFields()
            .then(async (value) => {
                let result = await reqAddUser(value)
                const { status, data, msg } = result
                if (status === 0) {
                    message.success("添加用户成功")
                    let userList = [...this.state.userList]  //克隆一个新用户列表
                    userList.unshift(data)   //此方法改变员数组
                    this.setState({ userList, isShowAdd: false })
                    this.form.resetFields()
                } else {
                    message.error(msg)
                }

            })
            .catch((err) => { })

    }
    handleCancel = () => {
        this.form.resetFields()
        this.setState({ isShowAdd: false })
    }

    componentDidMount() {
        this.getUserList()
    }
    //拿到用户列表
    getUserList = async () => {
        let result = await reqUserList()
        const { status, data } = result
        if (status === 0) this.setState({
            userList: data.users.reverse(),   //因为服务器是反的，所以需要反转 
            roleList: data.roles
        })
    }

    render() {
        const dataSource = this.state.userList

        const columns = [
            {
                title: '用户名',
                dataIndex: 'username',
                key: 'username',
            },
            {
                title: '邮箱',
                dataIndex: 'email',
                key: 'email',
            },
            {
                title: '电话',
                dataIndex: 'phone',
                key: 'phone',
            },
            {
                title: '注册时间',
                dataIndex: 'create_time',
                key: 'create_time',
                render: time => dayjs(time).format('YYYY年 MM月DD日 HH:mm:ss')
            },
            {
                title: '所属角色',
                dataIndex: 'role_id',
                key: 'role_id',
                //表格中的render 可以两个return，不影响
                render: (id) => {
                    let result = this.state.roleList.find((item) => {
                        return item._id === id
                    })
                    if (result) return result.name
                }
            },
            {
                title: '操作',
                dataIndex: 'operation',
                key: 'operation',
                render: () => {
                    return (
                        <>
                            <Button type='link'>修改</Button>
                            <Button type='link'>删除</Button>
                        </>
                    )
                }
            },
        ];
        return (
            <Card
                title={
                    <Button onClick={this.showModal} type='primary' style={{ borderRadius: '5px' }}><PlusOutlined />创建用户</Button>
                }
            >
                <Table
                    rowKey="_id"
                    bordered
                    dataSource={dataSource}
                    columns={columns}
                    pagination={{ pageSize: PAGE_SIZE }}
                />;
                <Modal
                    title="创建用户"
                    visible={this.state.isShowAdd}
                    onOk={this.handleOk}
                    onCancel={this.handleCancel}
                    okText="确认"
                    cancelText="取消"
                >
                    <Form
                        name="user"
                        labelCol={{ span: 4 }}
                        wrapperCol={{ span: 14 }}
                        ref={c => this.form = c}
                    >
                        <Item
                            label="用户名"
                            name="username"
                            rules={[{ required: true, message: '用户名不能为空!' }]}
                        >
                            <Input placeholder='请输入用户名' />
                        </Item>
                        <Item
                            label="密码"
                            name="password"
                            rules={[{ required: true, message: '密码不能为空!' }]}
                        >
                            <Input placeholder='请输入密码' />
                        </Item>
                        <Item
                            label="手机号"
                            name="phone"
                            rules={[{ required: true, message: '手机号不能为空!' }]}
                        >
                            <Input placeholder='请输入手机号码' />
                        </Item>
                        <Item
                            label="邮箱"
                            name="email"
                            rules={[{ required: true, message: '邮箱不能为空!' }]}
                        >
                            <Input placeholder='请输入邮箱' />
                        </Item>
                        <Item
                            label="角色"
                            name="role_id"
                            rules={[{ required: true, message: '角色不能为空!' }]}
                            initialValue=""
                        >
                            <Select>
                                <Option value="">请选择一个角色</Option>
                                {this.state.roleList.map((item) => {
                                    return <Option key={item._id} value={item._id}>{item.name}</Option>
                                })}
                            </Select>
                        </Item>
                    </Form>
                </Modal>
            </Card>
        )
    }
}
